package com.kaifamiao.demo.d0720;

public class Demo04 {

    public static void main(String[] args) {
        // 50 25 12 19 15 17 18


        // 排序好的数组才可以使用 二分搜索算法
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        int num = 0;
        int index = -1;

        int startIndex = 0;
        int endIndex = arr.length - 1;


        while(startIndex <= endIndex && index == -1){
            int middle = (startIndex + endIndex) >> 1;

            if (arr[middle] == num){
                index = middle;
            } else if(arr[middle] > num){
                endIndex = middle - 1;
            } else{
                startIndex = middle + 1;
            }
        }


        System.out.println(index);

    }

    public static int binarySearch(int[] arr, int num){
        int startIndex = 0;
        int endIndex = arr.length - 1;

        while(startIndex <= endIndex ){
            int middle = (startIndex + endIndex) >> 1;

            if (arr[middle] == num){
                return middle;
            } else if(arr[middle] > num){
                endIndex = middle - 1;
            } else{
                startIndex = middle + 1;
            }
        }

        return -1;
    }
}
